<template>
  <a-card title="角色选择">
    <a-list itemLayout="horizontal" :dataSource="listData">
      <a-list-item slot="renderItem" slot-scope="item">
        <el-checkbox v-model="item.check" @change="e => onChange(e, item)">{{ item.roleName }}</el-checkbox>
      </a-list-item>
    </a-list>
    <el-button type="primary" class="fr" @click="handleSaveRole">确定</el-button>
  </a-card>
</template>

<script>
import { queryAllRole } from '@/api/manage'
import { getSysPositionRole, updateSysPositionRole } from '@/api/department'
import { openNotification } from '@/utils/util'

export default {
  data() {
    return {
      listData: [],
      record: {}
    }
  },
  mounted() {
    queryAllRole().then(res => {
      this.listData = res.data
      this.changeBool(this.listData)
    })
  },
  methods: {
    changeBool(arr) {
      for (let a = 0; a < arr.length; a++) {
        this.$set(arr[a], 'check', false)
      }
    },
    async receiveOneRole(row) {
      this.record = Object.assign({}, row)
      // 用户点一个角色之后会去点另外一个，所以需要先清空listData的check属性
      this.changeBool(this.listData)
      const res = await getSysPositionRole({ deptId: row.deptId, positionId: row.positionId })
      if (res.data.length === 0) {
        return false
      }
      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < res.data.length; j++) {
          if (res.data[j].roleId === this.listData[i].roleId) {
            this.$set(this.listData[i], 'check', true)
          }
        }
      }
    },
    async handleSaveRole() {
      let arr = []
      this.listData.map(v => {
        if (v.check) {
          arr.push(v.roleId)
        }
      })

      const roleId = arr.join(',')
      const res = await updateSysPositionRole({ roleId, deptId: this.record.deptId, positionId: this.record.positionId })
      if (res.state === '000000') {
        openNotification('success', res.message)
        this.$emit('refresh')
      }

      this.$emit('changeShowPanel')
    },
    onChange(e, item) {
      console.log('e', e, item)
      const index = this.listData.findIndex(v => v.roleId === item.roleId)
      this.$set(this.listData[index], 'check', e)
    }
  }
}
</script>
